package controller.search;

import DateTools.DateUtil;
import domain.entity.ExecutionLog;
import domain.entity.TunnelBase;
import domain.entity.TunnelCompany;
import domain.entity.base.UserInfo;
import domain.entity.event.TunnelEventInfo;
import domain.service.base.ExecutionLogService;
import domain.service.base.TunnelBaseService;
import domain.service.base.TunnelCompanyService;
import domain.service.base.UserInfoService;
import domain.service.event.TunnelEventInfoService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import util.BaiduGeocoder;
import util.HttpRequestUtil;
import util.WebContextUtil;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * Created by bowen on 2016/7/28.
 */
@Controller
@RequestMapping(value = "/tunnel")
public class TunnelBaseController {

    private static final Logger logger = LoggerFactory.getLogger(TunnelBaseController.class);

    @Autowired
    private TunnelBaseService tunnelBaseService;

    @Autowired
    private TunnelCompanyService tunnelCompanyService;

    @Autowired
    private TunnelEventInfoService tunnelEventInfoService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private ExecutionLogService executionLogService;

    /**
     * @param r          搜索半径
     * @param searchType 类型
     * @return
     */
    @RequestMapping("getTunnelBaseList")
    @ResponseBody
    public List<Map<String, Object>> getTunnelBaseList(String point, String r, String searchType, HttpServletResponse response) throws Exception {
        String userId = WebContextUtil.getCurrentUser().getUserid();
        UserInfo userInfo = userInfoService.getUserInfoById(userId);
        searchType = new String(searchType.getBytes("ISO-8859-1"), "UTF-8");
        logger.info("------------------------------------------------------------");
        logger.info("point:" + point);
        logger.info("r:" + r);
        logger.info("searchType:" + searchType);
        logger.info("------------------------------------------------------------");
        response.setHeader("Access-Control-Allow-Origin", "*");
        double radius = Double.parseDouble(r);
        double point_lng = Double.parseDouble(point.split(",")[0]); //圆中心点经度
        double point_lat = Double.parseDouble(point.split(",")[1]);//圆中心点维度
        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
        String[] searchTypeArray = searchType.split(",");
        String log = "";
        for (String type : searchTypeArray) {
            if ("事件".equals(type)) {
                List<TunnelEventInfo> eventList = tunnelEventInfoService.getAllEvents(userId);
                for (TunnelEventInfo tunnelEventInfo : eventList) {
                    logger.info("--------tunnelEventInfo----------"+JSONObject.fromObject(tunnelEventInfo).toString()+"---------------------------------------");
                    double object_lng = Double.parseDouble(tunnelEventInfo.getLng()); //对象点经度
                    double object_lat = Double.parseDouble(tunnelEventInfo.getLat());//对象点维度
                    double distance = BaiduGeocoder.GetDistance(point_lat, point_lng, object_lng,object_lat );
                    logger.info("--------BaiduGeocoder----------"+distance+"---"+radius+"---------------------------------------");
                    if (distance <= radius) {
                        UserInfo ui = userInfoService.getUserInfoById(tunnelEventInfo.getEventUser());
                        Map<String, Object> resultMap = new HashMap<String, Object>();
                        resultMap.put("lng", object_lng);
                        resultMap.put("lat", object_lat);
                        resultMap.put("name", "");
                        resultMap.put("new", tunnelEventInfo.getTotal());
                        resultMap.put("type", "事件");
                        resultMap.put("userName", ui.getName());
                        resultMap.put("createTime", DateUtil.DateToString(tunnelEventInfo.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
                        resultMap.put("comment", tunnelEventInfo.getNote());
                        resultMap.put("id", tunnelEventInfo.getId());
                        logger.info("--------resultMap----------"+resultMap+"---------------------------------------");
                        resultList.add(resultMap);
                    }
                }
                if (userInfo != null) {
                    ExecutionLog executionLog = new ExecutionLog();
                    executionLog.setOpenid(userId);
                    executionLog.setUsername(userInfo.getName());
                    log = "用户" + userInfo.getName() + "于" + DateUtil.DateToString(new Date(), "yyyy-MM-dd HH:mm:ss") + "查看地图资源事件信息";
                    executionLog.setExe_log(log);
                    executionLogService.insert(executionLog);
                }
            }
            if ("公司".equals(type)) {
                List<TunnelCompany> tunnelBaseList = tunnelCompanyService.getTunnelCompanyList();
                for (TunnelCompany tunnelCompany : tunnelBaseList) {
                    double object_lng = Double.parseDouble(tunnelCompany.getLng()); //对象点经度
                    double object_lat = Double.parseDouble(tunnelCompany.getLat());//对象点维度
                    double distance = BaiduGeocoder.computedDistance(point_lat, point_lng, object_lat, object_lng);
                    if (distance <= radius) {
                        Map<String, Object> resultMap = new HashMap<String, Object>();
                        resultMap.put("lng", object_lng);
                        resultMap.put("lat", object_lat);
                        resultMap.put("name", tunnelCompany.getName());
                        resultMap.put("address", tunnelCompany.getAddress());
                        resultMap.put("type", "公司");
                        resultList.add(resultMap);
                    }
                }
                if (userInfo != null) {
                    ExecutionLog executionLog = new ExecutionLog();
                    executionLog.setOpenid(userId);
                    executionLog.setUsername(userInfo.getName());
                    log = "用户" + userInfo.getName() + "于" + DateUtil.DateToString(new Date(), "yyyy-MM-dd HH:mm:ss") + "查看地图资源公司信息";
                    executionLog.setExe_log(log);
                    executionLogService.insert(executionLog);
                }
            }
            if ("基地".equals(type)) {
                List<TunnelBase> tunnelBaseList = tunnelBaseService.getTunnelBaseList();
                for (TunnelBase tunnelBase : tunnelBaseList) {
                    double object_lng = Double.parseDouble(tunnelBase.getLng()); //对象点经度
                    double object_lat = Double.parseDouble(tunnelBase.getLat());//对象点维度
                    double distance = BaiduGeocoder.computedDistance(point_lat, point_lng, object_lat, object_lng);
                    if (distance <= radius) {
                        Map<String, Object> resultMap = new HashMap<String, Object>();
                        resultMap.put("lng", object_lng);
                        resultMap.put("lat", object_lat);
                        resultMap.put("name", tunnelBase.getName());
                        resultMap.put("address", tunnelBase.getAddress());
                        resultMap.put("type", "基地");
                        resultList.add(resultMap);
                    }
                }
                if (userInfo != null) {
                    ExecutionLog executionLog = new ExecutionLog();
                    executionLog.setOpenid(userId);
                    executionLog.setUsername(userInfo.getName());
                    log = "用户" + userInfo.getName() + "于" + DateUtil.DateToString(new Date(), "yyyy-MM-dd HH:mm:ss") + "查看地图资源基地信息";
                    executionLog.setExe_log(log);
                    executionLogService.insert(executionLog);
                }
            }
            if ("车辆".equals(type)) {
                Map<String, Object> parameterMap = new HashMap<String, Object>();
                parameterMap.put("lon", point_lng); //经度
                parameterMap.put("lat", point_lat); //维度
                parameterMap.put("range", r); //半径
                JSONObject jsonObject = HttpRequestUtil.sendClientRequest("getCarInfo", parameterMap);
                if (jsonObject != null) {
                    if (jsonObject.containsKey("code")) {
                        if (jsonObject.getInt("code") == 0) {
                            System.out.println("返回数据成功！" + jsonObject.toString());
                            JSONArray array = jsonObject.getJSONArray("result");
                            for (int i = 0; i < array.size(); i++) {
                                JSONObject object = array.getJSONObject(i);
                                Map<String, Object> resultMap = new HashMap<String, Object>();
                                resultMap.put("lng", object.getString("Lon_bd"));
                                resultMap.put("stype", object.getString("stype"));
                                resultMap.put("carno", object.getString("carno"));
                                resultMap.put("b_company", object.getString("b_company"));
                                resultMap.put("car_type", object.getString("type"));
                                resultMap.put("lat", object.getString("Lat_bd"));
                                resultMap.put("type", "车辆");
                                resultList.add(resultMap);
                            }
                        } else {
                            System.out.println("返回数据异常！" + jsonObject.toString());
                        }
                    }
                }
                if (userInfo != null) {
                    ExecutionLog executionLog = new ExecutionLog();
                    executionLog.setOpenid(userId);
                    executionLog.setUsername(userInfo.getName());
                    log = "用户" + userInfo.getName() + "于" + DateUtil.DateToString(new Date(), "yyyy-MM-dd HH:mm:ss") + "查看地图资源车辆信息";
                    executionLog.setExe_log(log);
                    executionLogService.insert(executionLog);
                }
            }
        }

        return resultList;
    }

}
